package com.lagou.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

public class SessionInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 获取用户名和密码
         */
        String userName = request.getParameter("userName");
        String pwd = request.getParameter("pwd");
        if(Objects.isNull(userName)){
            response.sendRedirect(request.getContextPath()+"/login");
        }else {
            String sessionId = request.getSession().getId();
            if(!redisTemplate.hasKey(sessionId)){
                redisTemplate.boundValueOps( sessionId).set(userName+"_"+pwd);
                Cookie cookie = new Cookie(sessionId,userName+"_"+pwd);
                response.addCookie(cookie);
            }else {
                String userInfo = (String) redisTemplate.boundValueOps(sessionId).get();
                Cookie cookie = new Cookie(sessionId,userInfo);
                response.addCookie(cookie);
            }
        }
        return true;
    }
}
